package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.DeviceControl_AirConditionActivity;
import com.argrace.smart.activity.DeviceModifyActivity;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.AirConditionEntity;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.ui.AirConditionView;
import com.argrace.smart.ui.AirCondition_RelationView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/3/9.
 */

public class DeviceRelation_AirConditionActivity extends BaseActivity {
    private ImageView img;
    MineZigBeeDeviceListEntity bean;
    private LinearLayout container;
    private ArrayList<AirCondition_RelationView> views = new ArrayList<>();
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;
    private String property;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_aircond);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = bean.getUuid();
        model = bean.getModel();
        property = getIntent().getStringExtra("property");
        setView();
        setTitle(true, false, "添加关联");
        showRight(true, R.mipmap.head_title_tick);
        //点击右上角保存此时设备状态与关联场景
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        //初始化后，数据库查询当前设备关联情况，无关联则查询最新状态
        if (false) {

        } else {
//            getDeviceDetailInfo();
        }
        addRelationView();

    }

    private void addRelationView() {
        AirCondition_RelationView ariView = new AirCondition_RelationView(this, bean.getUuid(),false);
        //+1使得position与sds平台的后缀相同
        ariView.setPosition(Integer.parseInt(property));
        container.addView(ariView);
        views.add(ariView);
    }

    private void save() {
        if (views.size() != 1) {
            toastActBtm("无法保存！");
            return;
        }
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setProperty(property);
        relationDeviceTable.setModel(model);
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append(views.get(0).getRelaitionJson());
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ? and property=?", uuid,property).find(LocalDb_RelationDeviceTable.class);
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
        finish();
        toastActBtm("保存成功");
    }
    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        container = (LinearLayout) findViewById(R.id.activity_devicecontrol_aircond_container);
        img.setImageResource(R.mipmap.bg_aircondition);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_AirConditionActivity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end

    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        AirConditionEntity entity = JSONObject.parseObject(obj.toString(), AirConditionEntity.class);
        if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI) && entity != null) {
            if (entity.getChannelCount() != null && entity.getChannelCount().getValue() != null) {
                int airsNum = Integer.parseInt(entity.getChannelCount().getValue());
                //relaition界面只有一个空调
//                for (int i = 0; i < airsNum; i++) {
                AirCondition_RelationView ariView = new AirCondition_RelationView(this, bean.getUuid(),false);
                    //+1使得position与sds平台的后缀相同
                    ariView.setPosition(Integer.parseInt(property));
                    container.addView(ariView);
                    views.add(ariView);
//                }
            }
            //根据entity更新界面数据,当前温度为-22到55，设定温度为16-32，开关0关闭1开启，模式1制冷2制热3送风4除湿，风俗2低3中4高
            //第一条空调数据
            Key_ValueEntity currentTemperature_1 = entity.getCurrentTemperature_1();
            Key_ValueEntity targetTemperature_1 = entity.getTargetTemperature_1();
            Key_ValueEntity switch_1 = entity.getSwitch_1();
            Key_ValueEntity workModel_1 = entity.getWorkMode_1();
            Key_ValueEntity windSpeed_1 = entity.getWindSpeed_1();
            if (currentTemperature_1 != null || targetTemperature_1 != null || switch_1 != null || workModel_1 != null || windSpeed_1 != null) {
                fillAirView(currentTemperature_1, targetTemperature_1, switch_1, workModel_1, windSpeed_1, views.get(0));
            }
        }
    }

    private void fillAirView(Key_ValueEntity currentTemperature, Key_ValueEntity targetTemperature, Key_ValueEntity switch_state, Key_ValueEntity workModel, Key_ValueEntity windSpeed, AirCondition_RelationView view) {
        if (currentTemperature != null && currentTemperature.getValue() != null) {
            view.getCurrentTemperature().setText((int) Float.parseFloat(currentTemperature.getValue()) + "℃");
        }
        if (targetTemperature != null && targetTemperature.getValue() != null) {
            view.getTagTemperature().setText((int) Float.parseFloat(targetTemperature.getValue()) + "℃");
        }
        if (switch_state != null && switch_state.getValue() != null) {
            if (switch_state.getValue().equals("0")) {
                view.getDrawableSwitch().setSwitchOn(false);
            } else {
                view.getDrawableSwitch().setSwitchOn(true);
            }
            view.getDrawableSwitch().invalidate();
        }

        if (workModel != null && workModel.getValue() != null) {
            view.setModel(workModel.getValue());
        }
        if (windSpeed != null && windSpeed.getValue() != null) {
            view.setWind(windSpeed.getValue());
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }
}
